//
//  Cityinfo.m
//  左邻右家
//
//  Created by 1 1 on 16/2/24.
//  Copyright © 2016年 Hiccup. All rights reserved.
//

#import "Cityinfo.h"


#import "CityInfo.h"
#import "QJZCity.h"
#import "QJZRegion.h"
#import "QJZCityGroup.h"
@implementation Cityinfo
static NSArray *_cities;
+ (NSArray *)cities {
    if (!_cities) {
        _cities = [[self alloc]getAndParseCityFile:@"cities.plist"];
    }
    return _cities;
}
- (NSArray *)getAndParseCityFile:(NSString *)fileName {
    NSArray *cityArray = [self getArrayFromPlistFile:fileName];
    
    //循环解析
    NSMutableArray *cityMutableArray = [NSMutableArray array];
    for (NSDictionary *cityDic in cityArray) {
        QJZCity *city = [QJZCity new];
        [city setValuesForKeysWithDictionary:cityDic];
        [cityMutableArray addObject:city];
    }
    
    return [cityMutableArray copy];
}
//从plist文件中读取数据，并赋值给数组
- (NSArray *)getArrayFromPlistFile:(NSString *)fileName {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    
    return array;
}
+ (NSArray *)regionsWithCityName:(NSString *)cityName {
    
    if (cityName.length == 0) {
        return nil;
    }
    //1.循环找到城市名字叫做cityName对应的那个城市模型对象TRCity
    NSArray *cityArray = [self cities];
    QJZCity *findedCity = [QJZCity new];
    for (QJZCity *city in cityArray) {
        if ([city.name isEqualToString:cityName]) {
            findedCity = city;
            break;
        }
    }
    
    //2.对TRCity中的区域数据进行解析 (NSDictionary -> TRRegion)
    NSArray *regionArray = findedCity.regions;
    
    //循环解析(NSDictionary -> TRRegion)
    NSMutableArray *regionMutableArray = [NSMutableArray array];
    for (NSDictionary *regionDic in regionArray) {
        QJZRegion *region = [QJZRegion new];
        [region setValuesForKeysWithDictionary:regionDic];
        [regionMutableArray addObject:region];
    }
    
    return [regionMutableArray copy];
}
static NSArray *_cityGroups;
+ (NSArray *)cityGroups {
    if (!_cityGroups) {
        _cityGroups = [[self alloc] getAndParseCityGroupFile:@"cityGroups.plist"];
    }
    return _cityGroups;
}
- (NSArray *)getAndParseCityGroupFile:(NSString *)fileName {
    NSArray *array = [self getArrayFromPlistFile:fileName];
    
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSDictionary *cityGroupDic in array) {
        QJZCityGroup *cityGroup = [QJZCityGroup new];
        [cityGroup setValuesForKeysWithDictionary:cityGroupDic];
        [mutableArray addObject:cityGroup];
    }
    return [mutableArray copy];
}
@end


